<?php
/**
 * Description: 获取课程组课程信息
 * User: devforma
 * Date: 16/7/12
 * Time: 14:23
 */
class GetGroupCourse implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (empty($queryArgs['group_id']) || filter_var($queryArgs['group_id'], FILTER_VALIDATE_INT) === false) {
            return genOutput(1000);
        }

        //获取该课程组下所有课程
        $courses = $cmsdb->getResults('SELECT * FROM `data_live_course` WHERE `course_group_id`=:gid AND `publish_status`="publish" ORDER BY `id` ASC', [':gid' => $queryArgs['group_id']]);
        if (empty($courses))
            return genOutput(1001);

        $resp = [
            'courses'        => [],
            'current_course' => 0
        ];

        $now = date('Y-m-d H:i:s');
        foreach ($courses as $course) {
            $resp['courses'][] = (int)$course->id;

            //在售时间限制
            $endTime = $course->end_day == '0000-00-00 00:00:00' ? $course->class_endtime : $course->end_day;
            if ($course->start_day > $now || $endTime < $now)
                continue;

            //购课人数限制
            if (($course->student_limit != -1 && $course->student_limit <= getCoursePurchasedPersons($course->id)))
                continue;

            //选择第一个符合条件的课程
            if (empty($resp['current_course']))
                $resp['current_course'] = (int)$course->id;
        }

        return genOutput(1, $resp);
    }
}